/**
 * 
 */
package com.uit.project.bustrip.bo;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.uit.project.bustrip.appconfig.AppsConfig;
import com.uit.project.bustrip.bointerface.TripBO;
import com.uit.project.bustrip.dao.TripDaoImpl;
import com.uit.project.bustrip.daointerface.TripDao;
import com.uit.project.bustrip.entity.Trip;
import com.uit.project.bustrip.ultil.JSONUltil;
import com.uit.project.bustrip.valueobject.JSONResult;

/**
 * @author Nguyen
 * 
 */
public class TripBOImpl extends BaseBOImpl<Trip, Integer> implements TripBO {
	public TripBOImpl() {
		super();
	}

	public TripBOImpl(Context context) {
		super(context);
	}

	@Override
	public Trip getInstance() {
		List<Trip> trip = ((TripDao) this.getDao()).findAll();
		if (trip.size() > 0)
			return trip.get(0);
		return null;
	}

	@Override
	public List<Trip> getAllTrip() {
		String url = getAllURL();
		JSONObject arrays = JSONUltil.getJSONObjectFromURL(url);
		if (arrays != null) {
			try {
				JSONArray jsonArray = arrays
						.getJSONArray(AppsConfig.JSON_OBJECT);
				TripDao tripDao = new TripDaoImpl();
				List<Trip> trips = new ArrayList<Trip>();
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = (JSONObject) jsonArray.get(i);
					Trip trip = tripDao.getFromJSON(jsonObject);
					trips.add(trip);
				}
				return trips;
			} catch (Exception e) {
				return null;
			}
		}
		return null;
	}

	public JSONResult getAllResultFromJson(JSONObject json) {
		JSONResult info = new JSONResult();
		try {
			info.setResult(json.getString(AppsConfig.JSON_RESULT));
			info.setMessage(json.getString(AppsConfig.JSON_MESSAGE));
			JSONArray jsonArray = json.getJSONArray(AppsConfig.JSON_DATA);
			TripDao tripDao = new TripDaoImpl();
			List<Trip> trips = new ArrayList<Trip>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				Trip trip = tripDao.getFromJSON(jsonObject);
				trips.add(trip);
			}
			info.setData(trips);
		} catch (Exception e) {
			Log.e("UserBOImpl - getLoginInfo", e.getMessage());
			return null;
		}
		return info;
	}

	private String getAllURL() {
		return AppsConfig.getServiceURL()
				+ "?_module=Trip&_action=list&_view=json";
	}

}
